package com.hjl.filter;

import com.hjl.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author ServivE
 * @version 0.1
 * @className CheckUserFilter
 * @description
 * @date 2024/7/26 11:33
 * @since jdk11
 */
@WebFilter(urlPatterns = "/admin/*")
public class CheckUserFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //将servletRequest转化为httpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获得session对象
        HttpSession session = request.getSession();
        //从session获取登录的时候存储的用户对象
        User user = (User) session.getAttribute("user");
        //放行
        if (user != null) {
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("放行");
        }else {
            //转发
            request.getRequestDispatcher("/login.html").forward(servletRequest,servletResponse);
            System.out.println("拦截成功");
        }
    }

    public void destroy() {

    }
}
